package offerbook;

import java.util.Stack;

/**
 * O(1)时间获取栈min。 额外空间O(n)
 */
public class Code21_GetStackMin {
    private Stack<Integer> dataStack = new Stack<>();
    private Stack<Integer> minStack = new Stack<>();

    public void push(int node) {
        dataStack.push(node);
        if(minStack.isEmpty()){
            minStack.push(node);
            return;
        }
        //比较栈顶和node谁小
        if(minStack.peek() > node){
            minStack.push(node);
        }else {
            minStack.push(minStack.peek());
        }
    }
    
    public void pop() {
        if(dataStack.isEmpty()) return;
        dataStack.pop();
        minStack.pop();
    }
    
    public int top() {
        if(dataStack.isEmpty()) throw new RuntimeException("empty");
        return dataStack.peek();
    }
    
    public int min() {
        if(minStack.isEmpty()) throw new RuntimeException("empty");
        return minStack.peek();
    }
}